#include "cJSON/cJSON.h"
#include "log/log.h"
#include <stdlib.h>

int main(int argc, char *argv[])
{
    //生成json字符串 
    char *name = "tom";
    int age = 12;

    //创建一个空的json对象
    cJSON *cjson_obj = cJSON_CreateObject();
    //向对象中添加键值对
    cJSON_AddStringToObject(cjson_obj, "name", name);
    cJSON_AddNumberToObject(cjson_obj, "age", age);
    //将json对象转换为字符串
    char *json_str = cJSON_PrintUnformatted(cjson_obj);
    //打印json字符串
    log_debug("json_str:%s", json_str);

    //解析json字符串
    cJSON *root = cJSON_Parse(json_str);
    if (root == NULL)
    {
        log_debug("cJSON_Parse failed");
        return -1;
    }
    //获取json对象中的值
    cJSON *name1 = cJSON_GetObjectItem(root, "name");
    cJSON *age1 = cJSON_GetObjectItem(root, "age");
    //判断值是否存在
    if (name1 == NULL || age1 == NULL)
    {
        log_debug("cJSON_GetObjectItem failed");
        return -1;
    }
    //打印值
    char *name2 = name1->valuestring;
    int age2 = age1->valueint;
    log_debug("name:%s, age:%d", name2, age2);

    //释放内存
    cJSON_Delete(cjson_obj);
    cJSON_Delete(root);
    free(json_str);

    return 0;
}